<?php

/**
 * alltosun.com 基本信息显示 setting.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址:   http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
 * $Date: 2015-1-18 下午6:03:19 $
 * $Id$
*/

class Action
{
    private $user_id;
    private $user_info;

    public function __construct()
    {
        $this->user_id = user_helper::get_user_id();
        $this->user_info = _uri('user', $this->user_id);
    }

    /**
     * 个人中心
     */
    public function __call($action = '', $param = array())
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        $user_info = $this->user_info;

        $cart_list = _widget('cart')->get_list();

        $order_has_list     = _widget('order')->get_list(array('progress'=>1, 'per_page'=>10));
        $order_express_list = _widget('order')->get_list(array('progress'=>15, 'per_page'=>10));
        $fav_list           = _Widget('fav')->get_list(array('per_page'=>6));

        //用户dz积分
        // $user_info['uc_credit'] = user_helper::uc_getcredit($user_info['uc_id']);

        Response::assign('fav_list', $fav_list);
        Response::assign('order_has_list', $order_has_list);
        Response::assign('order_express_list', $order_express_list);
        Response::assign('cart_list', $cart_list);
        Response::assign('user_info', $user_info);

        display_template('setting.html');
    }

    /**
     * ajax获取积分
     */
    public function get_credit()
    {
        $user_info = $this->user_info;
        $credit = user_helper::uc_getcredit($user_info['uc_id']);

        return array('info'=>'ok', 'credit'=>$credit);
    }

    /*
    * ajax获取用户消息数
    */
    public function get_pm_sum()
    {
        $user_info = $this->user_info;
        $pm_sum = user_helper::pm_checknew($user_info['uc_id']);
        return array('info'=>'ok', 'sum'=>$pm_sum);
    }


    /**
     * 基本信息修改
     */
    public function user_info()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }

        $user_info = $this->user_info;
        Response::assign('user_info', $user_info);
        display_template('user_info.html');
    }

    /**
    * 修改头像
    */
    public function edit_avatar()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }

        $user_info = $this->user_info;
        Response::assign('user_info', $user_info);
        Response::display('edit_avatar.html');
    }

    /*
    * 保存头像
    */

    public function avatar_save()
    {
        $user_id    = $this->user_id;
        if (!$user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        $file_name  = Request::getParam('file_name');
        $image_data = file_get_contents('php://input');
        if (!$image_data || !$file_name) {
            exit(json_encode(array('info'=>'图片上传失败')));
        }

        $folder = UPLOAD_PATH . '/avatar/' . $user_id;
        if (!file_exists($folder) && !@mkdir($folder, 0777, true)) {
            return false;
        }

        $file_name   = 'nbd_' . $user_id .'_avatar.jpg';
        $static_path = $folder . '/' . $file_name;

        //生成文件
        @file_put_contents($static_path, $image_data);

        $avatar_path = str_replace(UPLOAD_PATH, '', $static_path);
        $avatar_path = UPLOAD_URL.$avatar_path;
        $update_info = array();
        $update_info['avatar'] = $avatar_path;
        _model('user')->update($user_id, $update_info);

        // 添加动态
        //_widget('feed')->create('avatar', $user_id);

        $big_avatar_path = _image($avatar_path, 'big');
        if (strpos($big_avatar_path, SITE_URL) === false) {
            $big_avatar_path = SITE_URL.$big_avatar_path;
        }
        exit(json_encode(array('info'=>'ok', 'avatar'=>$big_avatar_path)));
    }

    /**
    * 修改用户信息
    */
    public function edit_user_info()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        $edit_type = Request::Get('edit_type', '');
        $user_info = $this->user_info;
        $birthday  = explode('-', $user_info['birthday']);
        Response::assign('edit_type', $edit_type);
        Response::assign('user_info', $user_info);
        Response::assign('birthday', $birthday);
        display_template('edit_user_info.html');

    }

    /**
     * 保存用户信息
     */
    public function save()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        $username = AnFilter::filter_string(trim(Request::Post('username', '')));
        $nickname = AnFilter::filter_string(trim(Request::Post('nickname', '')));
        $realname = AnFilter::filter_string(trim(Request::Post('realname', '')));
        $gender   = AnFilter::filter_string(trim(Request::Post('gender', '')));
        if(is_mobile() && !Request::isAjax()) {
            $day = trim(Request::Post('birthdayday', ''));
            if(strlen($day) == 1) {
                $day = '0'.$day;
            }
            $birthday = trim(Request::Post('birthdayyear', '')).'-'.trim(Request::Post('birthdaymonth', '')).'-'.$day;
        } else {
            $birthday = trim(Request::Post('birthday', ''));
        }
        $user_info = $this->user_info;

        $info = array();
        //用户修改用户名的次数
        $edit_user_num = user_config::$edit_user_num;
        if($user_info['edit_user_num'] < $edit_user_num && $user_info['user_name'] != $username && !empty($username)) {
            if(!user_helper::is_username_len($username)) {
                if(Request::isAjax()){
                    return array('info' => 'error', 'msg' => '您提交的用户名长度不符合要求！');
                }
                return array('您提交的用户名长度不符合要求！', 'error', AnUrl('user/setting/edit_user_info'));
            }
            if(user_helper::is_email($username)) {
                if(Request::isAjax()){
                    return array('info' => 'error', 'msg' => '您提交的用户名不能是邮箱！');
                }
                return array('您提交的用户名不能是邮箱！', 'error', AnUrl('user/setting/edit_user_info'));
            }
            if(!user_helper::is_username_unique($username)) {
                if(Request::isAjax()){
                    return array('info' => 'error', 'msg' => '您提交的用户名已经注册！');
                }
                return array('您提交的用户名已经注册！', 'error', AnUrl('user/setting/edit_user_info'));
            }
            if(user_helper::is_number($username)) {
                if(Request::isAjax()){
                    return array('info' => 'error', 'msg' => '您提交的用户名不能为纯数字！');
                }
                return array('您提交的用户名不能为纯数字！', 'error', AnUrl('user/setting/edit_user_info'));
            }
            $info['user_name'] = $username;
            $info['edit_user_num'] = ++$user_info['edit_user_num'];
        }

        if($birthday >= date('Y-m-d')){
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '生日不能大于当前时间。');
            }
            return array('生日不能大于当前时间。', 'error', AnUrl('user/setting/edit_user_info'));
        }
        $user_gender_type = user_config::$user_gender_type;

        if(!array_key_exists($gender, $user_gender_type)) {
            if(!Request::isAjax()){
                return array('参数错误', 'error', AnUrl('user/setting/edit_user_info'));
            }
        }
        if(Request::isAjax()){
            return array('info' => 'success');
        }
        $info['nickname'] = $nickname;
        $info['realname'] = $realname;
        $info['gender']   = $gender;
        $info['birthday'] = $birthday;
        $affected = _model('user')->update($this->user_id, $info);
        if($affected && isset($info['user_name'])) {
            user_helper::uc_edit($user_info['uc_id'], $info['user_name']);
        }

        return array('基本资料修改成功', 'success', AnUrl('user/setting/user_info'));
    }

    /**
    *  账号安全
    */
    public function account_safety()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        Response::assign('user_info', $this->user_info);
        display_template('account_safety.html');
    }

    /**
    * 帐号安全
    */
    public function edit_account()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        if(!$this->user_info['is_perfect']) {
            Response::redirect(AnUrl('openapi/index/bind'));
            return;
        }
        $edit_type = Request::Get('edit_type', '');
        if($edit_type == '') {
            return array('参数错误！', 'error', AnUrl('user/setting/account_safety'));
        }
        $edit_type_arr = user_config::$edit_type_arr;
        if(!in_array($edit_type, $edit_type_arr)) {
            return array('参数错误！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'set_password' && !empty($this->user_info['password'])) {
            return array('您已经设置过密码了！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'edit_password' && empty($this->user_info['password'])) {
            return array('请先直接设置密码！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'set_email' && !empty($this->user_info['email'])) {
            return array('您已经设置过邮箱了！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'edit_email' && empty($this->user_info['email'])) {
            return array('您还没设置过邮箱，请先设置邮箱！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'edit_email') {
            if($this->user_info['is_check_email']) {
                $email_code = _model('email_code')->read(array('email' => $this->user_info['email'], 'res_name' => 'check', 'user_id' => $this->user_id), 'ORDER BY `id` DESC');
                if(!$email_code || $email_code['status'] != 1) {
                    return array('请先验证原来的邮箱，才可以设置新的邮箱！', 'error', AnUrl('user/setting/account_safety'));
                }
            }
        }
        if($edit_type == 'edit_mobile' && empty($this->user_info['mobile'])) {
            return array('请直接设置新的手机号！', 'error', AnUrl('user/setting/account_safety'));
        }
        if($edit_type == 'set_mobile') {
            if(!empty($this->user_info['mobile'])) {
                $code_info = user_helper::getMobileCode($this->user_info['mobile'], 'edit', 1);
                if(!$code_info || $code_info['mobile'] != $this->user_info['mobile'] || $code_info['times']+600 < time()) {
                    return array('请先验证原手机号！', 'error', AnUrl('user/setting/account_safety'));
                }
            }
        }

        Response::assign('user_info', $this->user_info);
        Response::assign('edit_type', $edit_type);
        display_template('edit_account.html');
    }

    /**
     * 密码修改保存
     */
    public function password_save()
    {
        if (!$this->user_id) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '请登录后进行操作');
            }
            Response::redirect(AnUrl('user/login'));
        }
        $old_password = AnFilter::filter_string(trim(Request::Post('old_password', '')));
        $new_password = AnFilter::filter_string(trim(Request::Post('new_password', '')));
        $re_password  = AnFilter::filter_string(trim(Request::Post('re_password', '')));
        $edit_type    = AnFilter::filter_string(trim(Request::Post('edit_type', '')));
        if(!$this->user_info['is_perfect']) {
            Response::redirect('openapi/index/bind');
            return;
        }
        if(!in_array($edit_type, user_config::$edit_type_arr)) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '参数错误！');
            }
            return array('参数错误！', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if (!$this->user_id) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '请登录后进行操作');
            }
            return array('请登录后进行操作', 'error', AnUrl('user/login'));
        }
        if (!$old_password && $edit_type != 'set_password') {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '旧密码不能为空');
            }
            return array('旧密码不能为空', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if (!$new_password) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '新密码不能为空');
            }
            return array('新密码不能为空', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if (!$re_password) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '确认密码不能为空');
            }
            return array('确认密码不能为空', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if (!user_helper::is_strlen_scope($new_password, 6, 20)) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '新密码不能小于6位，大于20位字符。');
            }
            return array('新密码不能小于6位，大于20位字符。', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if ($new_password != $re_password) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '两次密码输入不一致');
            }
            return array('两次密码输入不一致', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if ($this->user_info['status'] != 1) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '该用户不存在或已禁用');
            }
            return array('该用户不存在或已禁用', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }

        if (user_helper::md5_password($old_password, $this->user_info['hash']) != $this->user_info['password'] && $edit_type != 'set_password') {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '原密码输入错误，请重新输入');
            }
            return array('原密码输入错误，请重新输入', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if($old_password == $new_password) {
            if(Request::isAjax()){
                return array('info' => 'error', 'msg' => '新密码不能和原密码一致。');
            }
            return array('新密码不能和原密码一致。', 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
        }
        if(Request::isAjax()){
            return array('info' => 'ok');
        }
        $hash = user_helper::random_hash(6);
        $affected = _model('user')->update($this->user_id, array('password'=>user_helper::md5_password($new_password, $hash), 'hash' => $hash));

        if($affected) {
            $return_info = user_helper::uc_edit($this->user_info['uc_id'], $this->user_info['user_name'], $this->user_info['email'], $new_password);
            if($return_info['info'] == 'ok') {
                if($edit_type == 'set_password') {
                    return array('设置成功', 'success', AnUrl('user/setting/account_safety'));
                } else {
                    return array('修改成功', 'success', AnUrl('user/setting/account_safety'));
                }
            } else {
                return array('ucenter:'.$return_info['msg'], 'error', AnUrl('user/setting/edit_account?edit_type='.$edit_type));
            }
        }

    }

    public function email_bind()
    {
        if (!$this->user_id) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'msg' => '请您登录后进行操作！');
            }
            Response::redirect(AnUrl('user/login'));
        }
        if(!$this->user_info['is_perfect']) {
            Response::redirect('openapi/index/bind');
            return;
        }
        $new_email = Request::Post('new_email', '');

        if(!user_helper::is_email($new_email)) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'msg' => '你输入的邮箱格式不正确');
            }
            return array('你输入的邮箱格式不正确', 'error', AnUrl('user/setting/edit_account?edit_type=set_email'));
        }
        if(!user_helper::is_email_unique($new_email)) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'msg' => '您输入的邮箱已经被绑定过了');
            }
            return array('您输入的邮箱已经被绑定过了', 'error', AnUrl('user/setting/edit_account?edit_type=set_email'));
        }
        // $affected = _model('user')->update($this->user_id, array('email' => $new_email, 'is_check_email' => '0'));
        // if($affected) {
            user_helper::set_mail_send($new_email, $this->user_id, 'edit');
        // }

        if(Request::isAjax()) {
            return array('info' => 'ok', 'msg' => '验证邮件已经发送到您的新邮箱，请及时验证。');
        }
        return array('验证邮件已经发送到您的新邮箱，请及时验证。', 'success', AnUrl('user/setting/account_safety'));
    }

    /**
    * 邮箱再次验证
    */
    public function send_check_email()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }

        if($this->user_info['is_check_email']) {
            return array('您已经验证过邮箱了', 'error', AnUrl('user/setting/account_safety'));
        }
        $return_info = user_helper::set_mail_send($this->user_info['email'], $this->user_id, 'edit');
        if($return_info) {
            return array('验证邮件已经发送到您的邮箱，请及时验证。', 'success', AnUrl('user/setting/account_safety'));
        } else {
            return array('验证邮件发送失败', 'error', AnUrl('user/setting/account_safety'));
        }
    }

    /**
    * 修改邮箱邮件发送
    */
    public function send_edit_email()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        if(!empty($this->user_info['email']) && !$this->user_info['is_check_email']) {
            Response::redirect(AnUrl('user/setting/edit_account?edit_type=edit_email'));
            return;
        }
        if(!empty($this->user_info['email']) && $this->user_info['is_check_email']) {
            $return_info = user_helper::set_mail_send($this->user_info['email'], $this->user_id, 'check');
            if($return_info) {
                return array('验证邮件已经发送到您的邮箱，请及时验证。', 'success', AnUrl('user/setting/account_safety'));
            } else {
                return array('验证邮件发送失败', 'error', AnUrl('user/setting/account_safety'));
            }
        } else {
            return array('访问错误！', 'error', AnUrl('user/setting/account_safety'));
        }

    }

    /**
    *  验证短信
    */
    public function check_sms()
    {
        if (!$this->user_id) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'type'=>'code','msg' => '请登录后进行操作');
            }
            Response::redirect(AnUrl('user/login'));
        }
        if(!$this->user_info['is_perfect']) {
            Response::redirect(AnUrl('openapi/index/bind'));
            return;
        }
        $code = trim(Request::Post('code', ''));
        $send_type = trim(Request::Post('send_type', ''));
        $mobile = $this->user_info['mobile'];
        if($send_type == 'check') { //如果是设置手机号码或者重新更改手机号码
            $mobile = trim(Request::Post('mobile', ''));
            if(empty($mobile)) {
                if(Request::isAjax()) {
                    return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机号码不能为空！');
                }
                return array('您填写的手机号码不能为空！', 'error', AnUrl('user/setting/edit_account?edit_type=set_mobile'));
            }
            if(!user_helper::is_mobile($mobile)) {
                if(Request::isAjax()) {
                    return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机号码格式不正确！');
                }
                return array('您填写的手机号码格式不正确！', 'error', AnUrl('user/setting/edit_account?edit_type=set_mobile'));
            }
            if(!user_helper::is_mobile_unique($mobile)) {
                if(Request::isAjax()) {
                    return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机号码已经被注册！');
                }
                return array('您填写的手机号码已经被注册！', 'error', AnUrl('user/setting/edit_account?edit_type=set_mobile'));
            }
        }

        if(empty($code)) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机验证码不能为空！');
            }
            return array('您填写的手机验证码不能为空！', 'error', AnUrl('user/setting/account_safety'));
        }
        $return_code = user_helper::getMobileCode($mobile, $send_type);
        if(($return_code['times'] + 600) <= time()) {
            if(Request::isAjax()) {
                return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机验证码已过期，请重新发送！');
            }
            return array('您填写的手机验证码已过期，请重新发送！', 'error', AnUrl('user/setting/account_safety'));
        }

        if($return_code['code']) {
            if($code != $return_code['code']) {
                if(Request::isAjax()) {
                    return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机验证码不正确！');
                }
                return array('您填写的手机验证码不正确！', 'error', AnUrl('user/setting/account_safety'));
            }
        } else {
            if(Request::isAjax()) {
                return array('info' => 'error', 'type'=>'code','msg' => '您填写的手机验证码不正确，请重新发送！');
            }
            return array('您填写的手机验证码不正确，请重新发送！', 'error', AnUrl('user/setting/account_safety'));
        }

        if(Request::isAjax()) {
            return array('info' => 'success');
        }
        if($send_type == 'edit') {
            _model('mobile_code')->update(array('mobile' => $mobile, 'code' => $code, 'res_name' => 'edit'), array('status' => 1));
            return array('验证成功', 'success', AnUrl('user/setting/edit_account?edit_type=set_mobile'));
        } else {
            $affected = _model('user')->update($this->user_id, array('mobile' => $mobile));
            if($affected) {
                $return_info = user_helper::uc_edit($this->user_info['uc_id'], $this->user_info['user_name'], '', '', $mobile, 10);
                if($return_info['info'] != 'ok') {
                    return array('ucenter:'.$return_info['msg'], 'error', AnUrl('user/setting/edit_account?edit_type=set_mobile'));
                } else {
                    _model('mobile_code')->update(array('mobile' => $mobile, 'code' => $code, 'res_name' => 'check'), array('status' => 1));
                    return array('验证成功', 'success', AnUrl('user/setting/account_safety'));
                }
            }

        }

    }

    /**
     * 账号绑定
     */
    public function account_bind()
    {
        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        if(!$this->user_info['is_perfect']) {
            return array('请完善信息后才可以绑定其他帐号。', 'error', AnUrl('openapi/index/bind'));
        }
        $baidu_info  = _uri('connect_baidu', array('user_id' => $this->user_id));
        $sina_info   = _uri('connect', array('user_id' => $this->user_id));
        $qq_info     = _uri('connect_qq', array('user_id' => $this->user_id));
        $weixin_info = _uri('connect_weixin', array('user_id' => $this->user_id));
        $lenovo_info = _uri('connect_lenovo', array('user_id' => $this->user_id));
        Response::assign('lenovo_info', $lenovo_info);
        Response::assign('baidu_info', $baidu_info);
        Response::assign('sina_info', $sina_info);
        Response::assign('qq_info', $qq_info);
        Response::assign('weixin_info', $weixin_info);
        Response::display('bind.html');
    }

    /**
     * 取消账号绑定
     */
    public function cancel_bind()
    {
        $site_id = Request::getParam('site_id', 0);

        if (!$this->user_id) {
            Response::redirect(AnUrl('user/login'));
        }
        if (!$site_id) {
            return array('参数错误！', 'error', AnUrl('user/setting/account_bind'));
        }

        $site_info = _uri('connect_site', $site_id);
        if(!$site_info) {
            return array('参数错误！', 'error', AnUrl('user/setting/account_bind'));
        }
        $user_info = $this->user_info;
        if(!$user_info['is_perfect']) {
            return array('您需要完善资料后才可以解绑第三方账号！', 'error', AnUrl('user/setting/account_bind'));
        }
        if(!$user_info['password']) {
            return array('您需要设置独立密码后才可以解绑第三方账号！', 'error', AnUrl('user/setting/account_bind'));
        }
        $connect_sql = $site_info['connect_sql'];

        $affected = _model($connect_sql)->delete(array('user_id' => $this->user_id, 'connect_site_id' => $site_id));
        if($affected) {
            return array('解绑第三方帐号成功！', 'success', AnUrl('user/setting/account_bind'));
        } else {
            return array('解绑第三方帐号失败！', 'error', AnUrl('user/setting/account_bind'));
        }
    }
}
?>